package com.server.modules.api.Base;

import com.server.common.persistence.Page;
import com.server.common.utils.ConstantUtils;
import com.server.common.utils.JedisUtils;
import com.server.common.utils.StringUtils;
import com.server.modules.api.vo.BaseQueryVo;
import com.server.modules.sys.entity.member.Member;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * xb_server
 * com.server.modules.api.Base
 * Created by wanglei on2016/8/9- 13:30.
 */
@Controller
public abstract class BaseAppController extends ServiceController{
	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());
	/**
	 * 返回封装数据
	 */
	// ============== 分页用的参数 =============
	protected int pageNum = 1; // 当前页

	protected int pageSize = 15; // 每页显示多少条记录

	/**
	 * 初始化pagebean
	 *
	 * @param page
	 * @return
	 */
	protected Page initPageBean(Page page) {
		if (page == null)
			page = new Page();
		if (page == null)
			page.setPageNo(1);
		if (page.getPageSize() == 0)
			page.setPageSize(15);
		return page;
	}

	/**
	 * 初始化pagebean
	 *
	 * @param pageSize
	 * @param currentPage
	 * @return
	 */
	protected Page initPageBean(Integer pageSize, Integer currentPage) {
		Page pageBean = new Page();
		Integer startIndex = null;
		if (currentPage == null) {
			currentPage = 1;
		}
		if (currentPage <= 0) {
			currentPage = 1;
			startIndex = -1;
		} else {
			startIndex = (currentPage - 1) * pageSize;
		}
		pageBean.setPageNo(currentPage);
		pageBean.setPageSize(pageSize);
		return pageBean;
	}

	protected void setPageConfig( BaseQueryVo vo) {
		if (vo.getCurrentPage()<= 0 || vo.getPageSize()<= 0) {
			vo.setPage(initPageBean(10, 1));
		} else {
			vo.setPage(initPageBean( vo.getPageSize(), vo.getCurrentPage()));
		}
	}
	protected boolean checkLogin(BaseQueryVo<T> vo) throws Exception {
		String memberId = vo.getMemberId();
		if (StringUtils.isNotEmpty(memberId)) {
			String sessionID = JedisUtils.get(memberId);
			if (sessionID == null){
				Member member = 	memberAPIService.get(memberId);
				if (member == null){
					return false;
				}else{
					sessionID = member.getSessionId();
					if (!StringUtils.isEmpty(sessionID)){
						JedisUtils.set(memberId,sessionID,0);
					}
				}
			}
			if ( vo.getSessionId().equals(sessionID)){
				return true;
			}else{
				return false;
			}
		}else {
			return false;
		}
	}
}
